﻿using Furion.DependencyInjection;
using Furion.FriendlyException;
using GoodAdmin.Core;

namespace GoodAdmin.AuthExtra;

public class DingUserService(DingToken dingToken, IGetUser getUser):ITransient
{
    private readonly DingToken dingToken = dingToken;
    private readonly IGetUser getUser = getUser;

    public async Task<DingdingUserEntity> GetDingdingUserDetail(string userId)
    {
        var token = await dingToken.GetAccessToken();
        var input = new DingdingUserInput
        {
            userid = userId,
        };
        var response = await getUser.GetUserDetailAsync(token, input);
        if (response.IsSuccessStatusCode)
        {
            string responseBody = await response.Content.ReadAsStringAsync();
            var userResult = responseBody.ToObject<DingdingBaseResult<DingdingUserEntity>>();
            if (userResult.errcode == 0)
            {
                return userResult.result;
            }
            else
            {
                throw Oops.Bah(userResult.errmsg);
            }
        }
        else
        {
            throw Oops.Bah("get user failed");
        }
    }

    public async Task<string> GetDingdingUserIdByAuthCode(string authCode)
    {
        var dingUserAuthCode = new DingUserAuthCode
        {
            code = authCode
        };
        var token = await dingToken.GetAccessToken();
        var response = await getUser.GetUserIdAsync(token, dingUserAuthCode);
        if (response.IsSuccessStatusCode)
        {
            string responseBody = await response.Content.ReadAsStringAsync();
            var userResult = responseBody.ToObject<DingdingBaseResult<DingUserGetByCodeResponse>>();
            if (userResult.errcode == 0)
            {
                return userResult.result.Userid;
            }
            else
            {
                throw Oops.Bah(userResult.errmsg);
            }
        }
        else
        {
            throw Oops.Bah("get user id by auth code failed");
        }
    }
}
